import { typeClassName } from '@/pages/config/classNameMap';
import { mapState } from 'vuex'
export default{
    computed: {
        ...mapState('admin/layout', ['currentAccount'])
    },
    methods: {
        loadPage (pageNavigation, filter, orderBy={}) {
            //删除查询项中属性值为空的查询条件
            this.tools.deleteInvalid(filter)
            filter = {
                className: this.className,
                type: this.type,
                ...filter,
                ...this.selfFilter // 页面本身写死的筛选条件
            }
            //区间查询
            let betweenFilter = ''
            Object.keys(filter).map(key=>{
                if(Array.isArray(filter[key])){
                    (filter[key][0]!==''||filter[key][1]!=='') && (betweenFilter=`&& ${key} between '${filter[key][0]}' and '${filter[key][1]}'`)
                    delete filter[key]
                }
            })
            let newFilter = '';
            if (this.tools.isReal(filter)) {
                newFilter = this.collectionObject.util.getFilter(filter);
                newFilter += betweenFilter;
            }
            this.loading = true;
            this.collectionObject
                .queryByPage(
                    pageNavigation.pageNumber,
                    pageNavigation.pageSize,
                    newFilter,
                    orderBy
                )
                .then((flag) => {
                    if (flag) {
                        this.pageNavigation.total = this.collectionObject.total;
                        this.loading = false;
                    } else {
                        this.loading = false;
                    }
            });
        },
        getRecord (filter) {
            let newFilter = this.collectionObject.util.getFilter(filter);
            return this.classObject.query(newFilter).then((flag) => {
                if (flag) {
                    return this.classObject.record;
                } else {
                    return false;
                }
            });
        },
        deleteRecord (ids) {
            let _this = this;
            this.loading = true;
            //是否有删除条件且满足
            if(typeof(this.deleteCondition)==='function'&&!this.deleteCondition(ids)){
                this.loading = false;
                return Promise.resolve()
            }
            return this.collectionObject.deleteByIds(ids).then((flag) => {
                if (flag) {
                    ids.forEach((id) => {
                        let index = _this.collectionObject.records.findIndex(
                            (item) => item.id === id
                        );
                        if (index !== -1) {
                            _this.collectionObject.records.splice(index, 1);
                        }
                    });
                    this.loading = false;
                    return true;
                } else {
                    this.loading = false;
                    return false;
                }
            });
        },
        handleSearch(filter) {
            this.pageNavigation.pageNumber = 1;
            this.loadPage(this.pageNavigation, filter,this.orderBy);
        },
        handleReset () {
            this.pageNavigation.pageNumber = 1;
            this.loadPage(this.pageNavigation, null,this.orderBy);
        },
        handleCreate () {
            this.$set(this.addNewPanel.drawer, 'show', true);
        },
        async handleNewAddSubmit (data) {
            //是否有新增确认条件且满足
            if(typeof(this.addCondition)==='function'&&!await this.addCondition(data)){
                return;
            }
            data.className = this.className;
            data.type = this.type;
            data.name = +new Date();
            // if (!this.selfFilter) {
            //     this.selfFilter = {}
            // }
            data.values = { ...data.values, ...this.defaultAddData, ...this.selfFilter }
            this.loading = true;
            this.classObject.add(data).then((flag) => {
                if (flag) {
                    this.collectionObject.records.unshift(this.classObject.record);
                    this.$set(this.addNewPanel.drawer, 'show', false);
                    this.loading = false;
                } else {
                    this.loading = false;
                }
            });
        },
        async handleEdit(row, index) {
            this.loading = true;
            if (await this.getRecord({ type: row.type, className: row.className, id: row.id })) {
                let detailData = this.tools.lodash.cloneDeep({
                    ...this.classObject.record,
                    ...this.classObject.record.values
                })
               
                for (let key in detailData) {
                    let item = detailData[key];
                    // 绑定人员的单独处理
                    if (Array.isArray(item) && !!item[0] && !!item[0].personId) {
                        detailData[key] = item.map(d => d.personName).join(',')
                    }
                }
                //是否有编辑弹框打开条件且满足
                if(typeof(this.editPanelOpenCondition)==='function'&&!this.editPanelOpenCondition(this.classObject.record)){
                    this.loading = false;
                    return;
                }
                console.log(this.classObject.record,"this.classObject.record");
                this.$set(this.editPanel, 'data', this.classObject.record);
                this.$set(this.editPanel.drawer, 'show', true);
                this.loading = false;
            } else {
                this.loading = false;
            }
        },
        async handleEditSubmit(data) {
            this.loading = true;
            //是否有编辑条件且满足
            if(typeof(this.editCondition)==='function'&& !await this.editCondition(data)){
                this.loading = false;
                return;
            }
            this.classObject.setRecord(data);
            return this.classObject.update().then((flag) => {
                if (flag) {
                    let index = this.collectionObject.records.findIndex(
                        (item) => item.id === this.classObject.record.id
                    );
                    if (index !== -1) {
                        this.collectionObject.records.splice(
                            index,
                            1,
                            this.classObject.record
                        );
                    }
                    this.loading = false;
                    this.$set(this.editPanel.drawer, 'show', false);
                } else {
                    this.loading = false;
                }
            });
        },
        async handleDetail (row, index) {
            this.loading = true;
            if (await this.getRecord({ type: row.type, className: row.className, id: row.id })) {
                let detailData = this.tools.lodash.cloneDeep({
                    ...this.classObject.record,
                    ...this.classObject.record.values
                })
                //是否有查看数据处理
                if(typeof(this.readDataCondition)==='function'){
                    this.readDataCondition(detailData);
                }
                for (let key in detailData) {
                    let item = detailData[key];
                    // 绑定人员的单独处理
                    if (Array.isArray(item) && !!item[0] && !!item[0].personId) {
                        detailData[key] = item.map(d => d.personName).join(',')
                    }
                }
                this.$set(this.readPanel, 'data', detailData);
                this.$set(this.readPanel.drawer, 'show', true);
                this.loading = false;
            } else {
                this.loading = false;
            }
        },
        handleDelete (row, index) {
            let _this = this;
            this.$Modal.confirm({
                title: this.lang['confirmDelete'],
                cancelText: this.lang['cancel'],
                onOk () {
                    _this.deleteRecord([row.id]);
                }
            })
        },
        async handleDeleteMultiple (selection) {
            let _this = this;
            this.$Modal.confirm({
                title: this.lang['confirmDelete'],
                cancelText: this.lang['cancel'],
                async onOk () {
                    let ids = [];
                    selection.map((item) => ids.push(item.id));
                    await _this.deleteRecord(ids).then((flag) => {
                        if (flag) {
                            _this.$refs.table.selection = [];
                        }
                    });
                }
            })
        },
        getModelType (type) {
            let modelType = ''
            if (type.startsWith('logic')) {
                modelType = 'logic'
            } else if (type.startsWith('template')) {
                modelType = 'template'
            } else if (type.startsWith('twins')) {
                modelType = 'twins'
            }
            return modelType;
        },
        // 获取下拉框
        getOptions (filter, classObject) {
            let newFilter = '';
            if (this.tools.isReal(filter)) {
                newFilter = classObject.util.getFilter(filter);
            }
            let statusOptions = []
            return classObject
                .query(newFilter)
                .then((flag) => {
                    if (flag) {
                        statusOptions = classObject.record.hier[0].basic.map(d => {
                            return {
                                label: d.title === null ? '' : d.title,
                                value: d.name === null ? '' : d.name
                            }
                        })
                    } else {
                        statusOptions = [];
                    }
                    return statusOptions;
            });
        },
        getOptionValue (options, value, key='label') {
          let dataValue = ''
          let index = options.findIndex(d => d.value === value)
          if (index !== -1) {
              dataValue = options[index][key];
          }
          return dataValue;
        },
        getOptionValueByArray (options, valueArray, key='label') {
            if (!!valueArray && Array.isArray(valueArray)) {
                let dataValue = ''
                valueArray.forEach(value => {
                    let index = options.findIndex(d => d.value === value)
                    if (index !== -1) {
                        dataValue += `${options[index][key]},`;
                    }
                })
                return dataValue;
            }
        },
        getModelTypeByType (type) {
            if (type.startsWith('template')) {
                return 'template'
            } else if (type.startsWith('logic')) {
                return 'logic'
            } else if (type.startsWith('twins')) {
                return 'twins'
            } else if (type.startsWith('entity')) {
                return 'entity'
            } else {
                return ''
            }
        },
        // 通过others获取关联的classObject
        getInfoByOthers () {
            this.others = this.classObject.others;
            if (!this.classObject.isValidOthers()) {
                return new Promise(resolve => resolve())
            }
            let pointer = this.others.basic[0].pointer;
            let modelType = this.getModelTypeByType(pointer.type)
            let { className, type, id } = pointer;
            let classObject = this.$modelObject.create(modelType);
            let newFilter = classObject.util.getFilter({ className, type, id });
            return classObject.query(newFilter).then((flag) => {
                if (flag) {
                    return classObject;
                } else {
                    return false;
                }
            });
        },
        // 时间带T带Z格式转换
        changeDate (dateA) {
            var dateee = new Date(dateA).toJSON();
            var date = new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '');
            return date;
        },
        // 添加hier中某项的接口
        hierAllAddRegister (pointer, newData, selectPanel) {
            this.loading = true;
            this.classObject
                .runAllAddRegister(pointer, { basic: newData })
                .then((flag) => {
                    if (flag) {
                        this.loading = false;
                        this.$set(selectPanel.drawer, 'show', false);
                    } else {
                        this.loading = false;
                    }
            });
        },
        //配置端写死的下拉框，通过title和name获取
        setOptions (classMapName, classObject, optionName) {
            let filter = {
                className: typeClassName[classMapName].className,
                type: typeClassName[classMapName].type
            }
            this.getOptions(filter, classObject).then(res => {
                this[optionName] = res
            })
        },
        /**
         * 功能说明：通过维护页面的数据获取下拉框，比如设备类型下拉框
         * classMapName:classNameMap.js中对照表
         * classObject：classObject
         * optionName：定义的下拉框数组名称
         * optionConfig：返回的hier取值对应的字段，比如label对应的sf_name,value对应的sf_code
         * optionConfig = {label:'sf_name',value:'sf_code'}
         */
        setOptionsByHier (classMapName, classObject, optionName, optionConfig = { label: 'sf_name', value: 'sf_code' }) {
            let filter = {
                className: typeClassName[classMapName].className,
                type: typeClassName[classMapName].type
            }
            let newFilter = '';
            if (this.tools.isReal(filter)) {
                newFilter = classObject.util.getFilter(filter);
            }
            let statusOptions = []
            return classObject
                .query(newFilter)
                .then((flag) => {
                    if (flag && classObject.isValidHier()) {
                        statusOptions = classObject.record.hier[0].basic.map(d => {
                            let option = {};
                            for (let key in optionConfig) {
                                option[key] = d.values[optionConfig[key]]
                            }
                            return option;
                        })
                    } else {
                        statusOptions = [];
                    }
                    this[optionName] = statusOptions
            });
        },
        /**
         * 通过hier中绑定项的className筛选已选中项
         */
        getSelectionByHierClassName (className) {
            let selectionData = [];
            if (!!this.classObject.hier && this.classObject.hier.length > 0) {
                selectionData = this.classObject.hier[0].basic.filter(d => d.pointer.className === className).map(d => {
                    return {
                        id: d.id,
                        label: d.values['sf_name'] || '',
                        code: d.values['code'] || d.values['sf_code'] || '',
                    }
                })
            }
            return selectionData;
        },
        // 当前账号与创建人和修改人不能为同一人
        isPermissionPerson (row) {
            let data = row||this.classObject.record
            if (this.currentAccount && this.currentAccount.account === data.createdBy) {
                return false;
            } else {
                return true;
            }
        },
    }
}
